import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class DioCase extends StatefulWidget {
  const DioCase({super.key});

  @override
  State<DioCase> createState() => _DioCaseState();
}

class _DioCaseState extends State<DioCase> {
  List<dynamic> channels = [];
  bool isLoading = false;
  String? errorMessage;

  Future<void> fetchData() async {
    setState(() {
      isLoading = true;
      errorMessage = null;
    });

    try {
      final dio = Dio();
      final response = await dio.get('https://geek.itheima.net/v1_0/channels');

      if (response.statusCode == 200) {
        setState(() {
          channels = response.data['data']['channels'];
          isLoading = false;
        });

        // 打印获取到的数据
        print('获取到 ${channels.length} 个频道');
        for (var channel in channels) {
          print('频道: ${channel['name']}');
        }
      }
    } on DioException catch (e) {
      setState(() {
        isLoading = false;
        errorMessage = '网络请求失败: ${e.message}';
      });
      print('Dio错误: $e');
    } catch (e) {
      setState(() {
        isLoading = false;
        errorMessage = '发生未知错误: $e';
      });
      print('其他错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 加载指示器
            if (isLoading) const CircularProgressIndicator(),

            // 错误信息
            if (errorMessage != null)
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red[50],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  errorMessage!,
                  style: const TextStyle(color: Colors.red),
                  textAlign: TextAlign.center,
                ),
              ),

            // 操作按钮
            ElevatedButton.icon(
              onPressed: isLoading ? null : fetchData,
              icon: const Icon(Icons.cloud_download),
              label: const Text('获取频道数据'),
              style: ElevatedButton.styleFrom(
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
              ),
            ),

            const SizedBox(height: 20),

            // 数据展示区域
            if (channels.isNotEmpty)
              Expanded(
                child: ListView.builder(
                  itemCount: channels.length,
                  itemBuilder: (context, index) {
                    final channel = channels[index];
                    return Card(
                      margin: const EdgeInsets.symmetric(vertical: 4),
                      child: ListTile(
                        leading: CircleAvatar(
                          backgroundColor: Colors.blue[100],
                          child: Text(
                            channel['name']?[0] ?? '?',
                            style: const TextStyle(color: Colors.blue),
                          ),
                        ),
                        title: Text(channel['name'] ?? '未知频道'),
                        subtitle: Text('ID: ${channel['id'] ?? '未知'}'),
                        trailing: const Icon(Icons.chevron_right),
                      ),
                    );
                  },
                ),
              ),

            // 空状态提示
            if (channels.isEmpty && !isLoading && errorMessage == null)
              const Column(
                children: [
                  Icon(Icons.cloud_off, size: 48, color: Colors.grey),
                  SizedBox(height: 8),
                  Text(
                    '暂无数据',
                    style: TextStyle(color: Colors.grey),
                  ),
                  Text(
                    '点击下方按钮获取频道信息',
                    style: TextStyle(color: Colors.grey, fontSize: 12),
                  ),
                ],
              ),
          ],
        ),
      ),
    );
  }
}
